<?php

namespace app\common\model;

use think\Model;

class UserClockIn extends Model
{
    // 表名
    protected $name = 'user_clock_in';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;

    // 追加属性
    protected $append = [
        'type_text'
    ];

    // 类型映射
    public function getTypeTextAttr($value, $data)
    {
        $type = [
            '1' => '学习',
            '2' => '申论'
        ];
        return isset($type[$data['type']]) ? $type[$data['type']] : '';
    }

    // 关联用户
    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id');
    }

    /**
     * 检查用户今天是否已打卡
     * @param int $user_id 用户ID
     * @param string $type 打卡类型
     * @return bool
     */
    public static function checkTodayClockIn($user_id, $type = null)
    {
        $where = [
            'user_id' => $user_id,
            'clock_in_date' => date('Y-m-d')
        ];
        if ($type !== null) {
            $where['type'] = $type;
        }
        return self::where($where)->count() > 0;
    }

    /**
     * 获取用户今日打卡记录
     * @param int $user_id 用户ID
     * @return array
     */
    public static function getTodayClockIn($user_id)
    {
        return self::where([
            'user_id' => $user_id,
            'clock_in_date' => date('Y-m-d')
        ])->select();
    }

    /**
     * 获取用户学习打卡总次数
     * @param int $user_id 用户ID
     * @return int
     */
    public static function getStudyClockInCount($user_id)
    {
        return self::where([
            'user_id' => $user_id,
            'type' => 1
        ])->count();
    }

    /**
     * 获取用户申论打卡总次数
     * @param int $user_id 用户ID
     * @return int
     */
    public static function getEssayClockInCount($user_id)
    {
        return self::where([
            'user_id' => $user_id,
            'type' => 2
        ])->count();
    }

    /**
     * 获取用户打卡总积分
     * @param int $user_id 用户ID
     * @param string|null $type 打卡类型，null为所有类型
     * @return int
     */
    public static function getTotalScore($user_id, $type = null)
    {
        $where = ['user_id' => $user_id];
        if ($type !== null) {
            $where['type'] = $type;
        }

        return self::where($where)->sum('score');
    }
}
